package com.guaju.yueshangLife.activity;

import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.os.Build;
import android.os.Bundle;
import android.os.Parcelable;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewCompat;
import android.support.v4.view.ViewPager;
import android.support.v4.view.WindowInsetsCompat;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.View;
import android.view.WindowManager;
import android.widget.AbsoluteLayout;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.ethanhua.skeleton.Skeleton;
import com.ethanhua.skeleton.ViewSkeletonScreen;
import com.guaju.yueshangLife.R;
import com.guaju.yueshangLife.adapter.CommonRecyclerViewAdapter;
import com.guaju.yueshangLife.base.BaseActivity;
import com.guaju.yueshangLife.base.GoodsDetail;
import com.guaju.yueshangLife.base.MyAppcomActivity;
import com.guaju.yueshangLife.bean.CartBean;
import com.guaju.yueshangLife.bean.GoodsDetailStringBean;
import com.guaju.yueshangLife.databinding.ActivityGoodsDetailBinding;
import com.guaju.yueshangLife.fragment.goods.CommentFragment;
import com.guaju.yueshangLife.fragment.goods.GoodsDetailFragment;
import com.guaju.yueshangLife.global.BaseApplication;
import com.guaju.yueshangLife.net.ApiEntity;
import com.guaju.yueshangLife.net.NetworkUtil;
import com.guaju.yueshangLife.utils.ToastUtil;
import com.guaju.yueshangLife.utils.Utils;
import com.guaju.yueshangLife.viewmodel.GoodsDetailVM;
import com.guaju.yueshangLife.widget.GoodsTopBar;
import com.guaju.yueshangLife.widget.MyCoordinatorLayout;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.Serializable;
import java.util.List;


public class GoodsDetailActivity extends MyAppcomActivity {
    private static final int SELECT_OPTION_IMMEDIATELY = 1002;
    public static final String GOODS_ID = "goods_id";
    public static final int RESULTCODE = 1003;
    public ActivityGoodsDetailBinding binding;
    Fragment[] mFragments = new Fragment[2];
    Toolbar mToolbar;
    private static int currentPage = 0;

    String[] mTitles = new String[]{
            "商品", "详情", "评价"
    };
    private int totalCartCount = 0;
    private MyCoordinatorLayout coordinator;
    private int headerHeight;
    private MinePagerAdapter minePagerAdapter;
    private GoodsDetailFragment goodsDetailFragment;
    private GoodsDetail.DataBean goodsDetailData;
    private String goods_id;
    private CommentFragment commentFragment;
    private View news_loading;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this, R.layout.activity_goods_detail);

        EventBus.getDefault().register(this);
        //一体栏
//        this.getWindow().addFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);

        /**
         * 暂时注释掉
         */
//        this.getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
//        this.getWindow().addFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
////
//        if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
//            ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.root_container_layout), new android.support.v4.view.OnApplyWindowInsetsListener() {
//                @Override
//                public WindowInsetsCompat onApplyWindowInsets(View v, WindowInsetsCompat insets) {
//                    return insets.consumeSystemWindowInsets();
//                }
//            });
//        }

//        setStatusBarColor(this,R.color.transparent);

//        addMarginTop(this);
        if (!NetworkUtil.isConnected(GoodsDetailActivity.this)) {
            startActivity(new Intent(this, NetErrorActivity.class));
            return;
        }

        realLogic();
        if (NetworkUtil.isConnected(GoodsDetailActivity.this)) {
            ApiEntity.cart();
        }


    }


    @Override
    protected void onResume() {
        super.onResume();

        if (NetworkUtil.isConnected(GoodsDetailActivity.this)) {
            ApiEntity.cart();
        }


    }

    private void realLogic() {
        mFragments[0] = GoodsDetailFragment.newInstance();


        goodsDetailFragment = (GoodsDetailFragment) mFragments[0];
        binding.goodsTopBar.setCurrentTab(0);
        binding.goodsTopBar.setVisibility(View.INVISIBLE);
        setupViewPager();
        setListener();
        initData();
    }

    private void setViewNormalStatus() {

        binding.goodsTopBar.setCurrentTab(0);
        binding.goodsTopBar.getBackground().setAlpha(0);//toolbar透明度初始化为0
    }


    private void setListener() {
        binding.goodsTopBar.setOnTabClickListener(new GoodsTopBar.OnMyTabClickListener() {
            @Override
            public void onTabClick(int position) {
                binding.goodsTopBar.setCurrentTab(position);
                switch (position) {
                    case 0:
                        if (currentPage == 0) {
                            ((GoodsDetailFragment) minePagerAdapter.getItem(0)).toggleToTop();
                        } else {
                            binding.viewpager.setCurrentItem(0);
                            currentPage = 0;
                        }
                        break;
                    case 1:
                        if (currentPage == 0) {
                            if (minePagerAdapter.getItem(0) instanceof GoodsDetailFragment) {
                                ((GoodsDetailFragment) minePagerAdapter.getItem(0)).toggleToButtom();
                            }
                        } else {
                            binding.viewpager.setCurrentItem(0);
                            currentPage = 0;
                        }
                        break;
                    case 2:
                        if (currentPage == 0) {
                            binding.viewpager.setCurrentItem(1);
                            currentPage = 1;
                        }
                        break;
                    default:
                        break;
                }

            }
        });
//        进入购物车按钮
        View ll_cart = binding.buyBottom.llCart;
        ll_cart.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(GoodsDetailActivity.this, CartActivity.class);
                startActivity(intent);
            }
        });


        //购物车按钮
        View fl_buy_cart = binding.buyBottom.flBuyCart;
        View fl_buy_immediately = binding.buyBottom.flBuyImmediately;
        View saveFav = binding.buyBottom.saveFav;

        fl_buy_cart.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //弹出buy窗口
                Intent intent = new Intent(GoodsDetailActivity.this, BuyActivity.class);
                BaseApplication.getInstance().setCurrentGoodDetail(goodsDetailData);
                startActivityForResult(intent, GoodsDetailFragment.SELECT_OPTION);
            }
        });

        fl_buy_immediately.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //弹出buy窗口
                BaseApplication.getInstance().setCurrentGoodDetail(goodsDetailData);
                Intent intent = new Intent(GoodsDetailActivity.this, BuyActivity.class);
                startActivityForResult(intent, SELECT_OPTION_IMMEDIATELY);
            }
        });
        binding.goodsError.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(GoodsDetailActivity.this, MainActivity.class);
                intent.putExtra(MainActivity.TAB_POSITION, 0);
                startActivity(intent);
                finish();
            }
        });
        saveFav.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        });

    }

    private void initData() {
        Intent intent = getIntent();
        if (intent != null) {
            goods_id = intent.getStringExtra(CommonRecyclerViewAdapter.GOODS_ID);
            ApiEntity.goodsDetailBean(goods_id);
            mFragments[1] = CommentFragment.newInstance(goods_id);
            commentFragment = (CommentFragment) mFragments[1];

        }
        GoodsDetailVM goodsDetailVM = new GoodsDetailVM();
    }

    private void setupViewPager() {
        minePagerAdapter = new MinePagerAdapter(getSupportFragmentManager());
        binding.viewpager.setOffscreenPageLimit(2);
        binding.viewpager.setAdapter(minePagerAdapter);
        binding.viewpager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {


            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            }

            @Override
            public void onPageSelected(int position) {
                if (1 == position) {
                    setCurrentTab(2);
                    binding.goodsTopBar.setVisibility(View.VISIBLE);


                } else {
                    setCurrentTab(1);
                    goodsDetailFragment.toggleInt();
                }

            }

            @Override
            public void onPageScrollStateChanged(int state) {
                if (state == ViewPager.SCROLL_STATE_DRAGGING || state == ViewPager.SCROLL_STATE_SETTLING) {
                    binding.goodsTopBar.setVisibility(View.VISIBLE);
                }

            }
        });
    }

    /**
     * ViewPager的PagerAdapter
     * 去除 , ContentDetailFragment.newInstance()
     */
    public class MinePagerAdapter extends FragmentPagerAdapter {


        public MinePagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            return mFragments[position];
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return mTitles[position];
        }

        @Override
        public int getCount() {
            return mFragments.length;
        }
    }


    public GoodsDetailFragment getGoodsDetailFragment() {
        return (GoodsDetailFragment) mFragments[0];
    }

    public CommentFragment getCommentFragment() {
        return (CommentFragment) mFragments[1];
    }

    public void setCurrentTab(int index) {
        binding.goodsTopBar.setCurrentTab(index);
        binding.viewpager.setCurrentItem(index == 2 ? 1 : 0);


    }

    @Override
    public void onDestroy() {
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onGoodsDetail(GoodsDetail goodsDetail) {
        if (goodsDetail != null) {
            getGoodsDetailFragment().updateView(goodsDetail);
            goodsDetailData = goodsDetail.getData();
            ApiEntity.cart();
            binding.goodsError.setVisibility(View.GONE);
            binding.llGoodsContainer.setVisibility(View.VISIBLE);

        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onGoodsDetail(GoodsDetailStringBean bean) {
        showEmpty();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onCartInfo(CartBean cartBean) {
        totalCartCount = 0;
        if (cartBean != null) {
            List<CartBean.DataBean> data = cartBean.getData();
            if (data != null && !data.isEmpty()) {
                for (CartBean.DataBean dataBean : data) {
                    totalCartCount += dataBean.getNumber();
                }
            }
            if (0 == totalCartCount) {
                binding.buyBottom.cartNums.setVisibility(View.GONE);
            } else {
                binding.buyBottom.cartNums.setVisibility(View.VISIBLE);
                binding.buyBottom.cartNums.setText(totalCartCount + "");
            }
            if (news_loading != null && news_loading.getVisibility() == View.VISIBLE) {
                news_loading.setVisibility(View.GONE);
            }

        }
    }

    //展示选择购物车
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == GoodsDetailFragment.SELECT_OPTION) {
//            Toast.makeText(this, "接收到购物车信息", Toast.LENGTH_SHORT).show();
            if (data != null) {
                int code = data.getIntExtra("code", 0);
                if (code == 200) {
//                    ToastUtil.show("添加购物车成功~");
                    String num = data.getStringExtra("num");
                    int i = 0;
                    if (!TextUtils.isEmpty(num)) {
                        i = Integer.parseInt(num);
                    }
                    String trim = binding.buyBottom.cartNums.getText().toString().trim();
                    int preNum = 0;
                    if (!TextUtils.isEmpty(trim)) {
                        try {
                            int i1 = Integer.parseInt(trim);
                            preNum = i1;
                        } catch (Exception e) {
                            preNum = 0;
                        }
                    }
                    preNum = preNum + i;
                    binding.buyBottom.cartNums.setVisibility(View.VISIBLE);
                    binding.buyBottom.cartNums.setText(preNum + "");
                }

            }
        }
    }

    private void showEmpty() {
        binding.llGoodsContainer.setVisibility(View.GONE);
        binding.goodsError.setVisibility(View.VISIBLE);

    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        goodsDetailFragment = null;
        commentFragment = null;
        finish();
    }
}
